package org.amos.filestorage.platform;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil;
import org.amos.filestorage.enums.FilePlatformEnum;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class FilePlatformManager {

    /**
     * key: platform唯一标识
     */
    private final ConcurrentMap<String, AbstractFilePlatform> platformMap = new ConcurrentHashMap<>();

    public <T extends FilePlatformConfig> AbstractFilePlatform<T> getPlatform(String platformId, String platform, T config) {
        AbstractFilePlatform<T> filePlatform = platformMap.get(platformId);
        if (filePlatform == null) {
            filePlatform = this.createFilePlatform(platformId, platform, config);
            platformMap.put(platformId, filePlatform);
        }
        if (filePlatform.init(config)) {
            platformMap.put(platformId, filePlatform);
        }

        return filePlatform;
    }

    private <T extends FilePlatformConfig> AbstractFilePlatform<T> createFilePlatform(String platformId, String platform, T config) {
        FilePlatformEnum platformEnum = FilePlatformEnum.getByPlatform(platform);
        Assert.notNull(platformEnum, String.format("文件配置(%s) 为空", platformEnum));
        // 创建客户端
        return (AbstractFilePlatform<T>) ReflectUtil.newInstance(platformEnum.getPlatformClass(), platformId, config);
    }
}
